package org.spring.springboot.app.user.sysuser.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.spring.springboot.app.base.R;
import org.spring.springboot.app.user.sysuser.service.IFindMailPassword;
import org.spring.springboot.app.base.Constants;
import org.spring.springboot.app.user.sysuser.domain.vo.*;
import org.spring.springboot.util.ApiIndex;
import org.spring.springboot.util.IdGen;
import org.spring.springboot.util.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.util.concurrent.TimeUnit;

@Api(description = "邮箱找回密码相关操作",tags = ApiIndex.FindMailPasswordController)
@RestController
public class FindMailPasswordController {

    @Autowired
    DefaultKaptcha defaultKaptcha;
    @Autowired
    RedisUtils redisUtils;
    @Autowired
    IFindMailPassword captchaService;

    @ApiOperation(value = "图片访问地址")
    @RequestMapping(value = "/captcha", method = RequestMethod.GET)
    public void captcha(@ApiParam(value = "验证码token", required = true) @RequestParam String captchaToken, HttpServletResponse httpServletResponse) throws Exception {
        byte[] captchaChallengeAsJpeg = null;
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            //生产验证码字符串并保存到redis中  
            String createText = defaultKaptcha.createText();
            if (StringUtils.isNotBlank(captchaToken)) {
                redisUtils.setString(Constants.MAIL_SEND_IMAGE_CODE_REDIS_KEY + captchaToken, createText, 5 * 60, TimeUnit.SECONDS);
            }
            //使用生产的验证码字符串返回一个BufferedImage对象并转为byte写入到byte数组中
            BufferedImage challenge = defaultKaptcha.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            httpServletResponse.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }
        //定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
        captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        httpServletResponse.setHeader("Cache-Control", "no-store");
        httpServletResponse.setHeader("Pragma", "no-cache");
        httpServletResponse.setDateHeader("Expires", 0);
        httpServletResponse.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream = httpServletResponse.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }

    @ApiOperation(value = "修改用户密码")
    @RequestMapping(value = "/modifyPassword", method = RequestMethod.PUT)
    public R modifyPassword(@RequestBody modifyMailPasswordReqVO vo) {
        return captchaService.modifyPassword(vo);
    }

    @ApiOperation(value = "发送邮箱")
    @RequestMapping(value = "/sendMail", method = RequestMethod.POST)
    public R<MailSendResVO> sendMail(@RequestBody MailSendReqVO vo) {
        return captchaService.sendMail(vo);
    }

    @ApiOperation(value = "校验邮箱验证码")
    @RequestMapping(value = "/validMailCode", method = RequestMethod.POST)
    public R<MailSendResVO> validMailCode(@RequestBody ValidMailReqVO vo) {
        return captchaService.validMailCode(vo);
    }

    @ApiOperation(value = "取得验证码图片token和验证码图片url地址")
    @RequestMapping(value = "/getCaptcha", method = RequestMethod.GET)
    public R<MailImageCodeResVO> captcha(HttpServletRequest request) {
        String path = request.getContextPath();
        String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
        R<MailImageCodeResVO> r = new R<MailImageCodeResVO>();
        String uuid = IdGen.uuid();
        MailImageCodeResVO c = new MailImageCodeResVO();
        c.setImageCaptchaToken(uuid);
        c.setImageCaptchaUrl(basePath + "captcha?captchaToken=" + uuid);
        r.setData(c);
        return r;
    }

}
